<?php

namespace app\api\controller;

use app\admin\model\shop\OrderAction;
use app\api\model\Order as OrderModel;
use app\api\model\OrderGoods as orderGoodsModel;
use app\common\controller\Api;
use think\Db;

/**
 * 订单接口
 */
class OrderRefund extends Api
{
    protected $noNeedRight = ['*'];

    public function detail()
    {
        $id = $this->request->param('id');
        if (empty($id)) {
            $this->error('参数缺失');
        }
        $row = orderGoodsModel::get($id, ['Order']);
        if (!$row) {
            $this->error('未找到记录');
        }
        if ($row->salestate && $row->salestate != 6) {
            $this->error('未拒绝，不能重复申请');
        }
        $order = $row->order;
        if (empty($order)) {
            $this->error('订单不存在');
        }
        if ($order->user_id != $this->auth->id) {
            $this->error('不可越权操作');
        }
        //订单正常，已发货，已支付
        if (in_array($order->orderstate, [0, 3, 4]) && $order->shippingstate && $order->paystate) {
            $row->visible(explode(',', 'id,order_sn,title,image,attrdata,price,nums'));
            $this->success('', $row);
        }
        $this->error('不允许的退款订单');
    }

    //申请售后
    public function apply()
    {
        $order_sn = $this->request->post('order_sn');
        $reason = $this->request->post('reason');
        $images = $this->request->post('images');
        $memo = $this->request->post('memo');

        $type = 1; //1=仅退款,2=退款退货

        if (empty($order_sn)) {
            $this->error('参数缺失');
        }
        if ($type != 1 && empty($reason)) {
//            $this->error('请输入售后原因');
        }

        $order = OrderModel::getByOrderSn($order_sn);

        if (!$order) {
            $this->error('订单不存在');
        }
        if ($order->salestate && $order->salestate != 6) {
            $this->error('未审核，不能重复申请');
        }

        if ($order->user_id != $this->auth->id) {
            $this->error('不可越权操作');
        }

        /*if($order->endtime>time()){
            $date = date('Y-m-d',time());
            $tomorrow = date('Y-m-d', strtotime('+1 day'));
            if ($order->date==$date){
                $this->error('已截单,当天订单不可申请退款');
            } elseif ($order->date==$tomorrow){
                $this->error('已截单,隔天订单不可申请退款');
            }
        }*/
        if ($order->shippingstate == 0 && $order->orderstate == 0 && $order->paystate == 1) {
            $cut_off_time = nl2br(Config('site.cut_off_time'));
            $end_time = strtotime("-1 day", strtotime($order->date));
            $end_time = date('Y-m-d '.$cut_off_time, $end_time);
            if (time() > strtotime($end_time)) {
                $this->error('已截单,不可申请退款');
            }
        }

        $realprice = $order['payamount'];

        $refundprice = $realprice;

        //订单正常，已发货，已支付
        if (in_array($order->orderstate, [0, 3, 4]) && $order->paystate) {
            if ($type != 1 && !$order->shippingstate) {
                $this->error('申请售后类型错误');
            }
            $reason = $type == 1 && empty($reason) ? '仅退款' : $reason;

            // 启动事务
            Db::startTrans();
            try {
                \app\api\model\OrderGoods::update(['salestate'=>2],['order_sn'=>$order->order_sn]);
                //$row->salestate = $type == 1 ? 2 : 1;
                //$row->save();
                $order->orderstate = 4;
                $order->salestate = 2;
                $order->save();

                //添加售后记录
                \app\admin\model\shop\OrderRefund::create([
                    'user_id'        => $this->auth->id,
                    'order_id'       => $order->id,
                    'type'           => $type,
                    'reason'         => $reason,
                    'realprice'      => $realprice,
                    'shippingfee'    => 0,
                    'refund'         => $refundprice,
                    'images'         => $images,
                    'memo'           => $memo
                ]);
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error('申请失败');
            }
            //记录操作
            OrderAction::push($order->order_sn, '用户', $type == 1 ? '申请退款' : '用户申请退款退货');
            $this->success('申请售后成功，等待审核');
        }
        $this->error('不允许的退款订单');
    }

    //查看售后
    public function aftersale()
    {
        $id = $this->request->param('id');
        if (empty($id)) {
            $this->error('参数缺失');
        }
        $row = \app\admin\model\shop\OrderRefund::where('order_id', $id)->find();
        if (empty($row)) {
            $this->error('未找到记录');
        }
        $order_info = \app\api\model\Order::get($row->order_id);
        $order = OrderModel::getDetail($order_info['order_sn'], $this->auth->id);
        $order->append(['status_text']);
        $order->hidden(explode(',', 'method,transactionid,updatetime,deletetime'));
        $data = [
            'refund_detail'=>$row,
            'order'=>$order
        ];
        $this->success('获取成功', $data);
    }

    //取消退款
    public function cancel()
    {
        $id = $this->request->param('id');
        if (empty($id)) {
            $this->error('参数缺失');
        }
        $row = \app\admin\model\shop\OrderRefund::where('order_id', $id)->find();
        if (empty($row)) {
            $this->error('未找到记录');
        }

        if ($row->status==2||$row->status==3){
            $this->error('已审核无法取消');
        }
        $order = \app\api\model\Order::get($id);

        \app\admin\model\shop\OrderGoods::where('order_sn', $order['order_sn'])->update(['salestate' => 0]);
        $order->salestate = 0;
        $order->orderstate = 0;
        $order->save();

        $this->success('取消成功');
    }

}
